package com.luhuihahaha.jsoupdemo.task;


import com.luhuihahaha.jsoupdemo.pojo.Item;
import com.luhuihahaha.jsoupdemo.service.ItemService;
import com.luhuihahaha.jsoupdemo.util.HttpUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ItemService itemService;

    //当我们的下载任务完成后经过多长时间进入下一次任务,单位是毫秒
    @Scheduled(fixedDelay = 100*1000)
    public void itemTask() throws Exception {

        //声明需要解析的初始地址
        String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1" +
                "&vt=2&wq=%E6%89%8B%E6%9C%BA&s=58&click=0&page=";

        //遍历页面对手机的搜索结果解析便利
        for (int i = 1; i < 10; i=i+2) {
            String html = httpUtils.doGetHtml(url + i);

            System.out.println(html);
            //解析页面获取商品数据
            this.parse(html);

        }
        System.out.println("手机数据抓取成功");

    }

    //解析页面获取商品数据
    private void parse(String html) {
        //解析html获取document对象
        Document document = Jsoup.parse(html);

        //获取spu
        Elements spuEles = document.select("div#J_goodsList > ul > li");


        for ( Element spuEle : spuEles) {
            //获取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));

            //获取sku
            Elements skuEles = spuEle.select("li.ps-item");

            for (Element skuEle : skuEles){
            //获取sku
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));

                //查询商品数据
                Item item = new Item();
                item.setSku(sku);
                List<Item> list = itemService.findAll(item);

                if (list.size()>0){
                    //如果商品存在 则进入下一次循环
                    continue;
                }

                //设置商品spu
                item.setSpu(spu);

                //设置商品详情链接url
                item.setUrl("https://item.paipai.com/+"+sku+"+.html");

                //设置商品图片
                String picUrl = skuEle.select("img[data-sku]").first().attr("src");
                System.out.println(picUrl+"----");
//                item.setPic(picUrl);
//                //商品价格
//                item.setPrice();
//                //商品标题
//                item.setTitle();
//
//                item.setCreated(new Date());
//                item.setUpdated(item.getCreated());



            }
        }


    }


}
